/**
 * Copyright (C) <2023> <Boundivore> <boundivore@foxmail.com>
 * <p>
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the Apache License, Version 2.0
 * as published by the Apache Software Foundation.
 * <p>
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * Apache License, Version 2.0 for more details.
 * <p>
 * You should have received a copy of the Apache License, Version 2.0
 * along with this program; if not, you can obtain a copy at
 * http://www.apache.org/licenses/LICENSE-2.0.
 */
import { useEffect, useState, useMemo } from 'react';
import { useSearchParams } from 'react-router-dom';
import { Popover, Checkbox, Typography, App } from 'antd';
import _ from 'lodash';
import RequestHttp from '@/api';
import APIConfig from '@/api/config';
import { fuzzySearchFiles, getKeyArrayReduce } from '@/utils/helper';
import type { TabsProps, CheckboxProps } from 'antd';
import { ConfigSummaryVo } from '@/api/interface';
import { t } from 'i18next';
import Base64 from 'crypto-js/enc-base64';
import Utf8 from 'crypto-js/enc-utf8';
import { removeByFilter } from '@/utils/helper';
import { useConfigState } from './useConfigState';
const { Paragraph } = Typography;

// 从 TabsProps 中提取 items 类型
type TabItem = NonNullable<TabsProps['items']>[number];

// 使用交叉类型将 ConfigSummaryVo 合并到 TabItem 中
type MergedTabItem = TabItem & ConfigSummaryVo;

export const useFileList = () => {
	const [searchParams] = useSearchParams();
	const id = searchParams.get('id');
	const serviceName = searchParams.get('name') || '';
	const [files, setFiles] = useState<string[]>([]);
	const [checkedList, setCheckedList] = useState<string[]>([]);
	const [allTabsData, setAllTabsData] = useState<MergedTabItem[]>([]);
	const [configData, setConfigData] = useState([]); // 存储原始数据
	const [tabsData, setTabsData] = useState<MergedTabItem[]>([]);
	const {
		activeTab,
		setActiveTab,
		setConfigGroupInfo,
		setActiveContent,
		setCodeEdit,
		setCodeVersion,
		setConfigPath,
		setCurrentGroupIndex,
		isConfigModified,
		setIsConfigModified
	} = useConfigState();

	const [pathList, setPathList] = useState<string[]>([]); //用于选择后批量下载
	const [allPathList, setAllPathList] = useState<string[]>([]); //用于全部下载
	const { modal } = App.useApp();

	// 获取初始数据
	const getConfigFile = async () => {
		const api = APIConfig.listSummary;
		const params = { ClusterId: id, ServiceName: serviceName };
		const data = await RequestHttp.get(api, { params });
		const { ConfigSummaryList } = data.Data;
		setConfigData(ConfigSummaryList); // 保存原始数据
	};
	//获取具体文件内容
	const getFileContent = async () => {
		const api = APIConfig.listByGroup;
		const { ConfigPath, Filename } = tabsData?.find(item => item.key === activeTab) ?? { ConfigPath: '' };
		const params = { ClusterId: id, ServiceName: serviceName, Filename, ConfigPath };
		const data = await RequestHttp.get(api, { params });
		const {
			Data: { ConfigGroupList }
		} = data;

		const copyData = _.cloneDeep(ConfigGroupList);
		const codeData = Utf8.stringify(Base64.parse(copyData[0].ConfigData));
		setActiveContent(copyData);
		setCodeEdit(codeData);
		setCodeVersion(copyData[0].ConfigNodeList[0].ConfigVersion);
		setConfigGroupInfo(copyData);
		setConfigPath(ConfigPath);
	};
	const handleSearch = (text: string) => {
		const result = fuzzySearchFiles(files, text);
		const filteredTabsData = allTabsData.filter(file => result.includes(file.Filename));
		setTabsData(filteredTabsData);
	};

	const handleChangeFile = (activeKey: string) => {
		if (isConfigModified) {
			modal.confirm({
				title: t('warning'),
				content: t('warningText'),
				okText: t('confirm'),
				cancelText: t('cancel'),
				onOk: async () => {
					setActiveTab(activeKey);
					setIsConfigModified(false);
					setCurrentGroupIndex(0);
				}
			});
		} else {
			setActiveTab(activeKey);
			setCurrentGroupIndex(0);
		}
	};

	const handleCheck: CheckboxProps['onChange'] = e => {
		const { checked, value } = e.target;
		let list: string[] = [];
		if (checked) {
			// 创建新数组,不要修改原数组
			list = [...checkedList, value];
		} else {
			// 过滤创建新数组
			list = removeByFilter(checkedList, value);
		}
		setCheckedList(list);
	};
	const checkAll = !!pathList.length && pathList.length === checkedList.length;
	const indeterminate = checkedList.length > 0 && checkedList.length < pathList.length;
	useEffect(() => {
		const paths = getKeyArrayReduce(tabsData, 'key');
		setPathList(paths);
	}, [tabsData]);
	const handleCheckAllChange: CheckboxProps['onChange'] = e => {
		setCheckedList(e.target.checked ? pathList : []);
	};
	useEffect(() => {
		getConfigFile();

		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [id, serviceName]);

	useEffect(() => {
		activeTab && getFileContent();
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [activeTab]);
	// 1. 处理基础数据
	const baseProcessedData = useMemo(() => {
		if (!configData.length)
			return {
				fileNames: [],
				tabs: [],
				allPathArr: []
			};

		const fileNames: string[] = [];
		const allPathArr: string[] = [];
		const tabs = configData.map((item: ConfigSummaryVo) => {
			fileNames.push(item.Filename);
			allPathArr.push(item.ConfigPath);
			return {
				...item,
				key: item.ConfigPath
			};
		});

		return { fileNames, tabs, allPathArr };
	}, [configData]); // 只依赖configData

	// 2. 处理带checkbox的tabs
	const processedTabs = useMemo(() => {
		return baseProcessedData.tabs.map(item => ({
			...item,
			label: (
				<div
					onClick={e => {
						e.stopPropagation();
					}}
				>
					<Checkbox
						className="mr-2"
						value={item.ConfigPath}
						onChange={handleCheck}
						checked={checkedList.includes(item.ConfigPath)}
					></Checkbox>
					<Popover
						placement="right"
						content={
							<Paragraph className="mb-0" copyable>
								{item.ConfigPath}
							</Paragraph>
						}
					>
						<span
							onClick={() => {
								handleChangeFile(item.ConfigPath);
							}}
						>
							{item.Filename}
						</span>
					</Popover>
				</div>
			)
		}));
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [baseProcessedData, checkedList]);

	// 3. 分开使用useEffect
	useEffect(() => {
		const { fileNames, tabs, allPathArr } = baseProcessedData;
		if (tabs.length) {
			setFiles(fileNames);
			setAllPathList(allPathArr);
			setActiveTab(tabs[0].key);
		}
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [baseProcessedData]);

	useEffect(() => {
		if (processedTabs.length) {
			setTabsData(processedTabs);
			setAllTabsData(processedTabs);
		}
	}, [processedTabs]);

	return {
		serviceName,
		files,
		tabsData,
		allTabsData,
		checkedList,
		checkAll,
		pathList,
		allPathList,
		indeterminate,
		getFileContent,
		handleSearch,
		handleCheckAllChange,
		handleChangeFile
	};
};
